﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Windows.Forms;
using System.Drawing;
using System.ComponentModel;
using System.Threading;

namespace GridViewTraceListener
{
    /// <summary>
    /// Sample Class to hold the 
    /// trace information to be displayed to the 
    /// gridview control
    /// </summary>
    public class TraceTable
    {



        public int Counter
        {
            get;
            set;
        }
        public string CreatedDate
        {
            get;
            set;
        }
        public string CreatedMessage
        {
            get;
            set;
        }
    }
    public class GridViewTraceListener : TraceListener
    {
        private SynchronizationContext _syncContext;
        private DataGridView GridViewControl;
        private Label LabelTotal;
        BindingList<TraceTable> bs = new BindingList<TraceTable>();
        public GridViewTraceListener(DataGridView output, Label labelTotal)
        {
            _syncContext = SynchronizationContext.Current;
            this.Name = "GridViewTraceListenerCtl";
            this.GridViewControl = output;
            this.LabelTotal = labelTotal;

            GridViewControl.DataSource = bs;
        }
        /// <summary>
        /// Put the code which involves updating the UI Here
        /// </summary>
        private void UpdateUI(object state)
        {
            TraceTable inp = new TraceTable();
            inp.Counter = ++TotalCount;
            inp.CreatedDate = DateTime.Now.ToString("hh:mm:ssss.ffff");
            inp.CreatedMessage = state as string;

            bs.Add(inp);
            LabelTotal.Text = TotalCount.ToString();
        }

        public static int TotalCount = 0;
        public override void Write(string message)
        {

            _syncContext.Send(UpdateUI, message);


        }

        public override void WriteLine(string message)
        {
            Write(message + Environment.NewLine);
        }
    }

}

